package com.ktwlrj.core.util;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ktwlrj.core.constant.ResultCode;
import com.ktwlrj.core.exception.ActionException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 二维码处理工具类
 *
 * @author zhouxuanhong
 * @date 2019-09-27 10:33
 * @since JDK1.8
 */
@Slf4j
public class QrCodeUtil {
    public static String createQrCode(String content, int qrCodeSize, String imageFormat) throws RuntimeException {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            Map<EncodeHintType, Object> hints = new HashMap<>(3);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.MARGIN, 1);
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hints);
            bitMatrix = deleteWhite(bitMatrix);
            BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
            ImageIO.write(image, imageFormat, os);
            return "data:image/" + imageFormat + ";base64," + Base64.encodeBase64String(os.toByteArray());
        } catch (WriterException | IOException e) {
            throw new ActionException(ResultCode.API_CODE_ERROR.getValue(), "生成二维码异常");
        }
    }


    /**
     * 识别二维码
     *
     * @param inputStream ${@link InputStream} 待识别图片
     * @return Map<String, String> ${@link Map<String, String>} success-true,false;msg-成功或失败原因;data-识别结果
     * @author zhouxuanhong
     * @date 2019-09-27 10:56
     */
    public static Map<String, String> checkoutQrCode(InputStream inputStream) throws IOException {
        Map<String, String> resultMap = new HashMap<>(3);
        if (inputStream == null) {
            resultMap.put("success", "false");
            resultMap.put("msg", "二维码不存在");
            return resultMap;
        }
        BufferedImage image = ImageIO.read(inputStream);
        LuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Map<DecodeHintType, Object> hints = new LinkedHashMap<>();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        Result result = null;
        try {
            result = new MultiFormatReader().decode(bitmap, hints);
        } catch (ReaderException e) {
            e.printStackTrace();
            resultMap.put("success", "false");
            resultMap.put("msg", "识别二维码异常");
            inputStream.close();
            return resultMap;
        }
        if (result == null) {
            resultMap.put("success", "false");
            resultMap.put("msg", "未识别出二维码信息");
            inputStream.close();
            return resultMap;
        }
        String text = result.getText();
        resultMap.put("data", text);
        resultMap.put("msg", "识别二维码成功");
        resultMap.put("success", "true");
        inputStream.close();
        return resultMap;
    }


    /**
     * 识别二维码
     *
     * @param imageUrl ${@link String} 图片地址
     * @return Map<String, String> ${@link Map<String, String>} success-true,false;msg-成功或失败原因;data-识别结果
     * @author zhouxuanhong
     * @date 2019-09-27 10:56
     */
    public static Map<String, String> checkoutQrCode(String imageUrl)
            throws IOException {
        Map<String, String> resultMap = new HashMap<>(3);
        resultMap.put("success", "true");
        resultMap.put("msg", "");
        resultMap.put("data", "");
        if (StringUtils.isBlank(imageUrl)) {
            resultMap.put("success", "false");
            resultMap.put("msg", "二维码地址为空");
            return resultMap;
        }
        log.debug("------------QrCodeUtil-----下载图片地址------->checkoutQrCode:{}", imageUrl);
        HttpURLConnection connection = (HttpURLConnection) new URL(imageUrl)
                .openConnection();
        connection.setReadTimeout(5000);
        connection.setConnectTimeout(5000);
        connection.setRequestMethod("GET");
        InputStream inputStream = null;
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            inputStream = connection.getInputStream();
        } else {
            resultMap.put("success", "false");
            resultMap.put("msg", "二维码不存在");
            if (inputStream != null) {
                inputStream.close();
            }
            return resultMap;
        }
        return checkoutQrCode(inputStream);
    }


    /**
     * 二维码去掉白边
     *
     * @param matrix ${@link BitMatrix}
     * @return BitMatrix ${@link BitMatrix}
     * @author zhouxuanhong
     * @date 2019-11-12 15:09
     */
    private static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;
        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1])) {
                    resMatrix.set(i, j);
                }
            }
        }
        return resMatrix;
    }


    public static void main(String[] args) throws IOException {
        String qrCode = QrCodeUtil.createQrCode("skdjflsdjf2323lsdfjlskdfl", 200, "png");
        System.out.println(qrCode);
//        FileInputStream fileInputStream = new FileInputStream(new File("/Users/zhou/Desktop/Jietu20190927-121658.png"));
////        System.out.println("----------Test---------->main:" + QrCodeUtil.checkoutQrCode(fileInputStream));
    }

}
